package com.fyzk.activity.chongzhi;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.chongzhi.epay.ResponseMessage;
import com.fyzk.activity.dialog.AppDialog;
import com.fyzk.activity.popupwindow.YHKZKPopup;
import com.fyzk.activity.user.userinfo.AuthenticationActivity;
import com.fyzk.base.BaseActivity;
import com.fyzk.bean.AccountMoneyResponse;
import com.fyzk.bean.AliPayResult;
import com.fyzk.bean.RechargeBankTransform;
import com.fyzk.bean.RechargeBean;
import com.fyzk.bean.RechargeChannelBean;
import com.fyzk.bean.UserInfoResponse;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.dialog.OfflineDialog;
import com.fyzk.net.Commands;
import com.fyzk.net.PublicMethod;
import com.fyzk.utils.Globle;
import com.fyzk.utils.HelpUrlConstants;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.PaymentUtil;
import com.fyzk.utils.update.CustomerCalls;
import com.fyzk.view.TopTitleView;
import com.shengpay.express.smc.enums.TransStatus;
import com.shengpay.express.smc.sign.RSA;
import com.shengpay.express.smc.utils.Constants;
import com.shengpay.express.smc.vo.OrderInfo;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;
import razerdp.basepopup.BasePopupWindow;

/**
 * 充值界面
 */
@ContentView(R.layout.ac_recharge)
public class RechargeActivity extends BaseActivity {

    private boolean chongzhi_islogin = false;

    @ViewInject(R.id.recharge_balance)
    private TextView recharge_balance;

    @ViewInject(R.id.recharge_rg_money)
    private RadioGroup recharge_rg_money;

    @ViewInject(R.id.recharge_rg_type)
    private RadioGroup recharge_rg_type;

    @ViewInject(R.id.recharge_edt_amount)
    private EditText recharge_edt_amount;

    @ViewInject(R.id.tv_tips)
    private TextView tv_tips;

    @ViewInject(R.id.recharge_tishi5_tv)
    private TextView recharge_tv5_infor;

    @ViewInject(R.id.recharge_tishi6_tv)
    private TextView recharge_tv6_infor;

    @ViewInject(R.id.ll_normal)
    private LinearLayout ll_normal;

    @ViewInject(R.id.ll_bank)
    private LinearLayout ll_bank;

    @ViewInject(R.id.ll_more)
    private LinearLayout ll_more;

    @ViewInject(R.id.ll_recharge_bank2)
    private LinearLayout ll_recharge_bank2;
    @ViewInject(R.id.ll_recharge_bank)
    private LinearLayout ll_recharge_bank;
    @ViewInject(R.id.ll_recharge_wechat)
    private LinearLayout ll_recharge_wechat;
    @ViewInject(R.id.ll_recharge_ebank)
    private LinearLayout ll_recharge_ebank;
    @ViewInject(R.id.ll_recharge_exchange_alipay)
    private LinearLayout ll_recharge_exchange_alipay;
    @ViewInject(R.id.ll_recharge_wap)
    private LinearLayout ll_recharge_wap;
    @ViewInject(R.id.ll_recharge_exchange_bank)
    private LinearLayout ll_recharge_exchange_bank;
    @ViewInject(R.id.ll_recharge_sftpay)
    private LinearLayout ll_recharge_sftpay;
    @ViewInject(R.id.recharge_h5)
    private LinearLayout h5_ll;

    @ViewInject(R.id.recharge_channel_list_ll)
    private LinearLayout rechargeChannel_ll;    // 渠道列表父控件

    private WebView textView;
    private RelativeLayout zhiFuBao_wap;
    private RelativeLayout zhiFuBao_express;
    private ImageView iv_zhifubao;
    private ImageView iv_zhifubao_express;
    private RelativeLayout yiBao;
    private RelativeLayout chz_center_jd;
    private ImageView iv_yibao;
    private RelativeLayout yinLian;
    private ImageView iv_yinlian;

    private TopTitleView chz_top_rl;

    private String realName = "";

    private static final int WHAT_USER = 0;
    private AlertDialog vipDialog;

    private UserInfoResponse userInfoResponse;

    private String orderId = "";    // 投注订单号
    private long lowMoney = 0;       // 投注差额

    private String payTypeTitle = "在线支付";

    // 最小充值彩金
    private final int MINCHARGEAMOUNT = 2;
    private final int MAXCHARGEAMOUNT = 1000;

    //客服QQ
//    private String serviceQQ = "";
    //客服电话
//    private String servicePhone = "";
    private boolean isFirst = true;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        orderId = getIntent().getStringExtra(IntentParamUtils.ORDER_ID);
        lowMoney = getIntent().getLongExtra(IntentParamUtils.lowMoney, 0);

//        serviceQQ = AppUtil.getFormatStr(
//                App.getContext().getResources().getString(R.string.recharge_tishi5),
//                MySharedPreferences.getInstance().getServiceQQ());
//        servicePhone = AppUtil.getFormatStr(
//                App.getContext().getResources().getString(R.string.recharge_tishi6),
//                MySharedPreferences.getInstance().getServicePhone());

        info();
        recharge_edt_amount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (isFirst) {
                    recharge_edt_amount.setText("");
                }
                isFirst = false;
            }
        });
    }

    private void requestUserInfo() {
        httpPostJson(CommandUtil.USERINFO, Commands.USERINFO, null, false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (TextUtil.isEmpty(rechargeChannel)) {
            getRechargeChannel();
        }
        if (userInfoResponse == null) {
            requestUserInfo();
        }
        requestLeftMoney();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    private int resultActivityCode = 0;

    @Override
    public void finish() {
        if (!TextUtil.isEmpty(orderId) && lowMoney > 0) {   // 投注彩金不足，充值
            setResult(resultActivityCode, getIntent());
        }
        super.finish();
    }

    @Override
    public void onLeftClick() {
        resultActivityCode = IntentParamUtils.LOWMONEY_TO_RECHARGE_FAIL;
        super.onLeftClick();
    }

    @Override
    public void onBackPressed() {
        resultActivityCode = IntentParamUtils.LOWMONEY_TO_RECHARGE_FAIL;
        super.onBackPressed();
    }

    @Override
    public void onRightClick() {
        super.onRightClick();
        WebView webView = new WebView(this);
        webView.setPadding(20, 0, 20, 0);
        webView.loadUrl(HelpUrlConstants.RECHARGE_LIMIT);
        AlertDialog dialog = new AlertDialog.Builder(this).setTitle("限额说明").setView(webView)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).create();
        dialog.show();
    }

    /**
     *
     */
    private void info() {

        textView = (WebView) findViewById(R.id.web_view_alipay);

        recharge_rg_money.setOnCheckedChangeListener(amountChangedListener);
//        recharge_rg_money.check(R.id.recharge_money_200);
//        recharge_rg_money.check(R.id.recharge_money_50);
        recharge_rg_type.setOnCheckedChangeListener(rechargeTypeChangedListener);

        CustomerCalls customerCalls = MySharedPreferences.getInstance().getCustomerCalls();
        if (customerCalls != null) {
            tv_tips.setText(customerCalls.getTips());
        }

        chz_top_rl = (TopTitleView) findViewById(R.id.chz_top_rl);
        chz_top_rl.setOnTitleClickListener(this);
        zhiFuBao_wap = (RelativeLayout) findViewById(R.id.chz_center_zhifubao_wap);
        zhiFuBao_express = (RelativeLayout) findViewById(R.id.chz_center_zhifubao_expresss);
        yiBao = (RelativeLayout) findViewById(R.id.chz_center_yibao);
        yinLian = (RelativeLayout) findViewById(R.id.chz_center_yinlian);
        chz_center_jd = (RelativeLayout) findViewById(R.id.chz_center_jd);

        iv_zhifubao = (ImageView) findViewById(R.id.chz_center_iv_zhifubao);
        iv_zhifubao_express = (ImageView) findViewById(R.id.chz_center_iv_zhifubao_express);
        iv_yibao = (ImageView) findViewById(R.id.chz_center_iv_yibao);
        iv_yinlian = (ImageView) findViewById(R.id.chz_center_iv_yinlian);

        zhiFuBao_express.setOnClickListener(new ChongZhiOnClick());
        zhiFuBao_wap.setOnClickListener(new ChongZhiOnClick());
        yiBao.setOnClickListener(new ChongZhiOnClick());
        chz_center_jd.setOnClickListener(new ChongZhiOnClick());
        yinLian.setOnClickListener(new ChongZhiOnClick());

        ll_recharge_sftpay.setOnClickListener(this);
        ll_recharge_wap.setOnClickListener(this);
        ll_recharge_bank2.setOnClickListener(this);
        ll_recharge_bank.setOnClickListener(this);
        ll_recharge_wechat.setOnClickListener(this);
        ll_recharge_ebank.setOnClickListener(this);
        ll_recharge_exchange_alipay.setOnClickListener(this);
        ll_recharge_exchange_bank.setOnClickListener(this);

        Globle.setHW(zhiFuBao_wap, 1015, 150, this);
        Globle.setHW(zhiFuBao_express, 1015, 150, this);
        Globle.setHW(yiBao, 1015, 150, this);
        Globle.setHW(yiBao, 1015, 150, this);
        Globle.setHW(yinLian, 1015, 150, this);

        Globle.setHW(iv_zhifubao, 268, 111, this);
        Globle.setHW(iv_zhifubao_express, 268, 111, this);
        Globle.setHW(iv_yibao, 268, 111, this);
        Globle.setHW(iv_yinlian, 268, 111, this);
        textView.loadUrl("file:///android_asset/alipay_exchange.html");
        recharge_balance.setText("账户彩金:" + MySharedPreferences.getInstance().getBalance() + "米");
//        recharge_tv5_infor.setText(serviceQQ);
//        recharge_tv6_infor.setText(servicePhone);

        if (!TextUtil.isEmpty(orderId) && lowMoney > 0) {
            recharge_rg_money.setVisibility(View.GONE);
            recharge_edt_amount.setText(lowMoney + "");
            recharge_edt_amount.setEnabled(false);
        } else {
//            recharge_rg_money.setVisibility(View.VISIBLE);
            recharge_rg_money.setVisibility(View.GONE);
        }

        h5_ll.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), RechargeNewActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 获取充值渠道
     */
    private void getRechargeChannel() {
        httpPostJson(CommandUtil.RECHARGECHANNEL, Commands.NEWRECHARGECHANNEL, null, true);
    }


    protected void rechargeAlipay(String money, String payChannel) {
        try {
            JSONObject params = new JSONObject();
            params.put("amount", money);
            params.put("payChannel", payChannel);
            params.put("cardType", "APP-ALIPAY-P2P");
            params.put("orderId", orderId);
            httpPostJson(CommandUtil.RECHARGE_ALIPAY_EXPRESS, Commands.USERPAY, params, true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected void rechargeAlipaySDK(String money, String payChannel, String cardType) {
        try {
            JSONObject params = new JSONObject();
            params.put("amount", money);
            params.put("payChannel", payChannel);
            params.put("cardType", cardType);
            params.put("orderId", orderId);
            httpPostJson(CommandUtil.RECHARGE_ALIPAY_SDK, Commands.USERPAY, params, true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected void rechargeWap(String money, String payChannel, String cardType) {
        try {
            JSONObject params = new JSONObject();
            params.put("amount", money);
            params.put("payChannel", payChannel);
            params.put("cardType", cardType);
            params.put("orderId", orderId);
            httpPostJson(CommandUtil.RECHARGE, Commands.USERPAY, params, true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 银行卡转卡
     *
     * @param money
     * @param payChannel
     * @param cardType
     */
    protected void rechargeYHKZK(String money, String payChannel, String cardType, String userName) {
        try {
            JSONObject params = new JSONObject();
            params.put("amount", money);
            params.put("payChannel", payChannel);
            params.put("cardType", cardType);
            params.put("orderId", orderId);
            params.put("userName", userName);
            httpPostJson(CommandUtil.RECHARGE_YHKZK, Commands.USERPAY, params, true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected void rechargeSftpay(String money) {
        try {
            JSONObject params = new JSONObject();
            params.put("amount", money);
            params.put("authtoken", MySharedPreferences.getInstance().getAuthtoken());
            params.put("payChannel", "sftpay");
            params.put("cardType", "");
            params.put("orderId", orderId);
            httpPostJson(CommandUtil.RECHARGE_SFTPAY, Commands.USERPAY, params, true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void requestLeftMoney() {
        httpPostJson(CommandUtil.ACCOUNT_MONEY, Commands.ACCOUNT_MONEY, null, true);
    }


    /**
     * 充值验证
     *
     * @return
     */
    private boolean rechargeYanZheng(String money) {
        if (TextUtil.isEmpty(money)) {
            recharge_edt_amount.setError("请输入彩金");
            return false;
        }
        if (!TextUtil.isEmpty(orderId) && lowMoney > 0) {

        } else {    // 正常充值判断最低、最高彩金
//            if (Integer.parseInt(money) < MINCHARGEAMOUNT) {
//                AlertDialog limitAlert = new AlertDialog.Builder(this).setTitle("提示").setMessage
//                        (String.format("最低充值彩金为%s米", MINCHARGEAMOUNT)).setPositiveButton("继续", new DialogInterface.OnClickListener() {
//
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.cancel();
//                    }
//                }).create();
//                limitAlert.show();
//                recharge_edt_amount.setText(String.valueOf(MINCHARGEAMOUNT));
//                recharge_edt_amount.setSelection(String.valueOf(MINCHARGEAMOUNT).length());
//                return false;
//            }
//            if (Integer.parseInt(money) > MAXCHARGEAMOUNT) {
//                showToast(String.format("最大充值彩金%s米", MAXCHARGEAMOUNT));
//                recharge_edt_amount.setText(String.valueOf(MAXCHARGEAMOUNT));
//                return false;
//            }
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        String money = recharge_edt_amount.getText().toString();
        if (TextUtil.isEmpty(money)) {
            recharge_edt_amount.setError("请输入彩金");
            return;
        }
        if (!TextUtil.isEmpty(orderId) && lowMoney > 0) {

        } else {    // 正常充值判断最低、最高彩金
//            if (Integer.parseInt(money) < MINCHARGEAMOUNT) {
//                AlertDialog limitAlert = new AlertDialog.Builder(this).setTitle("提示").setMessage
//                        (String.format("最低充值彩金为%s米", MINCHARGEAMOUNT)).setPositiveButton("继续", new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.cancel();
//                    }
//                }).create();
//                limitAlert.show();
//                recharge_edt_amount.setText(String.valueOf(MINCHARGEAMOUNT));
//                recharge_edt_amount.setSelection(String.valueOf(MINCHARGEAMOUNT).length());
//                return;
//            }
//            if (Integer.parseInt(money) > MAXCHARGEAMOUNT) {
//                showToast(String.format("最大充值彩金%s米", MAXCHARGEAMOUNT));
//                recharge_edt_amount.setText(String.valueOf(MAXCHARGEAMOUNT));
//                return;
//            }
        }

        switch (v.getId()) {
            case R.id.ll_recharge_bank2:
            case R.id.ll_recharge_bank:
                break;
            case R.id.ll_recharge_wechat:
                break;
            case R.id.ll_recharge_ebank:
//                rechargeAlipay(money, "yeebaonew");
                rechargeAlipaySDK(money, "wf", "zfbsdk");
                break;
            case R.id.ll_recharge_wap:
                rechargeWap(money, "yeebaonew", "ALIPAY-WAP-P2P");
                break;
            case R.id.ll_recharge_sftpay:
                if (userInfoResponse != null && !userInfoResponse.getRealName().equals("") &&
                        !userInfoResponse.getIdcard()
                                .equals("")) {

                    rechargeSftpay(money);
                } else {
                    AppDialog.getDialog()
                            .showPerfectInforDialog(getContext(), new AppDialog
                                    .OnAppDialogClickListener() {

                                @Override
                                public void onSureClick() {
                                    Intent intent2 = new Intent(
                                            getContext(),
                                            AuthenticationActivity.class);
                                    intent2.putExtra("userinfo", userInfoResponse);
                                    startActivity(intent2);
                                }

                                @Override
                                public void onCancleClick() {
                                }
                            });
                }
//                rechargeSftpay(money);
                break;
            case R.id.ll_recharge_exchange_alipay:
                break;
            case R.id.ll_recharge_exchange_bank:
                if (vipDialog == null) {
                    WebView view = (WebView) View.inflate(this, R.layout.chongzhi_vip, null);
                    view.loadUrl(HelpUrlConstants.VIP_RECHARGE);
                    vipDialog = new AlertDialog.Builder(RechargeActivity.this).setTitle("Vip转账")
                            .setView(view).setPositiveButton("确定", new DialogInterface
                                    .OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            }).create();
                }
                vipDialog.show();
                break;
        }

    }

    String rechargeChannel;
    private List<RechargeChannelBean> rechargeChannelBeans = new ArrayList<>();

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.RECHARGECHANNEL:
//                try {
//                    JSONObject obj = new JSONObject(resultBean.getData());
//                    if (obj.has("rechargeChannel")) {
//                        rechargeChannel = obj.getString("rechargeChannel");
//                        if (rechargeChannel != null) {
//                            if (rechargeChannel.contains("yeebaonew")) {    // 支付宝充值
//                                ll_recharge_ebank.setVisibility(View.VISIBLE);
//                                ll_recharge_wap.setVisibility(View.VISIBLE);
//                            } else {
//                                ll_recharge_ebank.setVisibility(View.GONE);
//                                ll_recharge_wap.setVisibility(View.GONE);
//                            }
//                            if (rechargeChannel.contains("sftpay")) {       // 盛付通充值
//                                ll_recharge_sftpay.setVisibility(View.VISIBLE);
//                            } else {
//                                ll_recharge_sftpay.setVisibility(View.GONE);
//                            }
//                        }
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }

                // 新充值渠道接口返回
                rechargeChannelBeans = JSON.parseArray(resultBean.getData(), RechargeChannelBean.class);
                rechargeChannel_ll.removeAllViews();
                for (int i = 0; i < rechargeChannelBeans.size(); i++) {
                    rechargeChannel_ll.addView(getRechargeChannelView(rechargeChannelBeans.get(i)));
                }

                break;
            case CommandUtil.RECHARGE_ALIPAY_EXPRESS:
            case CommandUtil.RECHARGE_ALIPAY_SDK:
                try {
                    JSONObject obj = new JSONObject(resultBean.getData());
                    String resultJs = obj.getString("result");

                    if (result == null) {
                        ResponseMessage.sendExceptionMessage(ResponseMessage.RESPONSE, handler);
                        return;
                    }
                    if (null == payHandler)
                        payHandler = new AliPayHandler(RechargeActivity.this);
                    PaymentUtil.getInstance()
                            .aliPay(RechargeActivity.this, resultJs, payHandler);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case CommandUtil.RECHARGE_YHKZK://银行卡转卡
                RechargeBankTransform bankTransform = JSON.parseObject(resultBean.getData(), RechargeBankTransform.class);
                String money = recharge_edt_amount.getText().toString();
                bankTransform.setMoney(money);
                Intent bankIntent = new Intent(RechargeActivity.this, BankTransformActivity.class);
                bankIntent.putExtra("bank", bankTransform);
                startActivity(bankIntent);
                break;
            case CommandUtil.RECHARGE:
                // 新充值渠道接口返回
                RechargeBean rechargeBean = JSON.parseObject(resultBean.getData(), RechargeBean.class);
                if ("线下支付".equals(payTypeTitle)) {
                    showOfflineDialog(rechargeBean);
                } else {
                    String redicturl = rechargeBean.getResult();
                    if (result == null) {
                        ResponseMessage.sendExceptionMessage(ResponseMessage.RESPONSE, handler);
                        return;
                    }
//                    Intent intent = new Intent(RechargeActivity.this, RechargeNewActivity.class);
//                    intent.putExtra("url", redicturl);
//                    intent.putExtra("title", payTypeTitle);
//                    intent.putExtra("money", recharge_edt_amount.getText().toString());
//                    startActivityForResult(intent, CommandUtil.RECHARGE);
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse(redicturl));
                    startActivity(intent);
                }
                break;
            case CommandUtil.RECHARGE_SFTPAY:
                try {
                    if (resultBean.getErrorcode().equals("0")) {
                        JSONObject obj = new JSONObject(resultBean.getData());
                        JSONObject resultJs = new JSONObject(obj.getString("result"));
                        LogUtil.v("充值：" + resultJs);
                        String privateKey = resultJs.getString("privateKey");
                        resultJs.remove("privateKey");
                        resultJs.remove("signMsg");
                        resultJs.remove("outMemberName");
                        resultJs.put("outMemberName", realName);
                        LogUtil.v("RSA前：" + resultJs.toString());
                        final OrderInfo orderinfo = JSON.parseObject(resultJs.toString(), OrderInfo
                                .class);
                        String signMsg = RSA.sign(orderinfo.getSignOriginal(), privateKey, "UTF-8");
                        orderinfo.setSignMsg(signMsg);
                    } else {
                        showToast("数据异常");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {

                }
                break;
            case CommandUtil.USERINFO:
                userInfoResponse = JSON.parseObject(resultBean.getData(),
                        UserInfoResponse.class);
                realName = userInfoResponse.getRealName();
                break;
            case CommandUtil.ACCOUNT_MONEY:
                AccountMoneyResponse accountMoneyResponse = JSON.parseObject(resultBean.getData(),
                        AccountMoneyResponse.class);
                MySharedPreferences.getInstance().setBalance(PublicMethod
                        .formatBalance(accountMoneyResponse
                                .getBalance()));
                MySharedPreferences.getInstance().setDrawbalance(PublicMethod
                        .formatBalance(accountMoneyResponse
                                .getDrawbalance()));
                MySharedPreferences.getInstance().setFreeze(PublicMethod
                        .formatBalance(accountMoneyResponse
                                .getFreeze()));
                recharge_balance.setText("账户彩金:" + MySharedPreferences.getInstance().getBalance() + "米");
                break;

        }

    }

    private void showOfflineDialog(RechargeBean rechargeBean) {
        OfflineDialog mDialog = new OfflineDialog(this, rechargeBean);
        mDialog.show();
    }

    /**
     * 获取渠道控件
     *
     * @param rechargeChannel
     * @return
     */
    private View getRechargeChannelView(final RechargeChannelBean rechargeChannel) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.view_recharge_channel, null);
        LinearLayout channel_ll = view.findViewById(R.id.recharge_channel_ll);
        ImageView icon_iv = view.findViewById(R.id.recharge_channel_icon);
        TextView name_tv = view.findViewById(R.id.recharge_channel_name);

//        TextView description_tv = view.findViewById(R.id.recharge_channel_description);
//        description_tv.setVisibility(rechargeChannel.getDescription().equals("") ? View.GONE : View.VISIBLE);
//        description_tv.setText(rechargeChannel.getDescription());

//        if (rechargeChannel.getPayType().equals("h5pay")) {
//            icon_iv.setImageResource(R.drawable.icon_h5pay);
//            name_tv.setText("网页支付");
//        }
//
//        if (rechargeChannel.getPayType().equals("zfbsdk")) {
//            icon_iv.setImageResource(R.drawable.icon_alipayexpress);
//            name_tv.setText("支付宝[稳定][推荐]");
//        }
//
//        if (rechargeChannel.getPayType().equals("zfbwap")) {
//            icon_iv.setImageResource(R.drawable.icon_alipayexpress);
//            name_tv.setText("支付宝快捷");
//        }
//
//        if (rechargeChannel.getPayType().equals("webchatsm")) {
//            icon_iv.setImageResource(R.drawable.icon_wechat_pay);
//            name_tv.setText("微信支付");
//        }
//
//        if (rechargeChannel.getPayType().equals("webchatwap")) {
//            icon_iv.setImageResource(R.drawable.icon_wechat_pay);
//            name_tv.setText("微信支付");
//        }
//
//        if (rechargeChannel.getPayType().equals("unionscan")) {
//            icon_iv.setImageResource(R.drawable.icon_unionpay);
//            name_tv.setText("银联扫码");
//        }
//
//        if (rechargeChannel.getPayType().equals("unionkj")) {
//            icon_iv.setImageResource(R.drawable.icon_unionpay);
//            name_tv.setText("银联快捷");
//        }
//
//        if (rechargeChannel.getPayType().equals("offline")) {
//            icon_iv.setImageResource(R.drawable.icon_offlinepay);
//            name_tv.setText("线下支付");
//        }
//
//        if (rechargeChannel.getPayType().equals("yhkzk")) {
//            icon_iv.setImageResource(R.drawable.icon_yhkzk);
//            name_tv.setText("银行卡转卡");
//        }

        name_tv.setText(rechargeChannel.getPayName());

        if (rechargeChannel.getPayName().contains("支付宝")) {
            icon_iv.setImageResource(R.drawable.icon_alipayexpress);
        } else if (rechargeChannel.getPayName().contains("微信")) {
            icon_iv.setImageResource(R.drawable.icon_wechat_pay);
        } else if (rechargeChannel.getPayName().contains("银联")) {
            icon_iv.setImageResource(R.drawable.icon_unionpay);
        } else if (rechargeChannel.getPayName().contains("银行卡")) {
            icon_iv.setImageResource(R.drawable.icon_yhkzk);
        } else if (rechargeChannel.getPayName().contains("线下")) {
            icon_iv.setImageResource(R.drawable.icon_offlinepay);
        }

        channel_ll.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                String money = recharge_edt_amount.getText().toString();
                payTypeTitle = "H5支付";
                if (rechargeChannel.getPayType().equals("h5pay")) {
                    if (rechargeYanZheng(money)) {
                        Intent intent = new Intent(getContext(), RechargeNewActivity.class);
                        intent.putExtra("url", rechargeChannel.getH5url());
                        intent.putExtra("title", payTypeTitle);
                        intent.putExtra("money", money);
                        startActivity(intent);
                    }
                } else if (rechargeChannel.getPayType().equals("zfbsdk")) {
                    payTypeTitle = "支付宝支付";
                    if (rechargeYanZheng(money)) {
//                        rechargeWap(money, rechargeChannel.getPayChannel(), rechargeChannel.getCardType());
                        rechargeAlipaySDK(money, rechargeChannel.getPayChannel(), rechargeChannel.getCardType());
                    }
                } else if (rechargeChannel.getPayType().equals("zfbwap")) {
                    payTypeTitle = "支付宝支付";
                    if (rechargeYanZheng(money)) {
                        rechargeWap(money, rechargeChannel.getPayChannel(), rechargeChannel.getCardType());
                    }
                } else if (rechargeChannel.getPayType().equals("webchatwap")) {
                    payTypeTitle = "微信支付";
                    if (rechargeYanZheng(money)) {
                        rechargeWap(money, rechargeChannel.getPayChannel(), rechargeChannel.getCardType());
                    }
                } else if (rechargeChannel.getPayType().equals("webchatsm")) {
                    payTypeTitle = "微信支付";
                    if (rechargeYanZheng(money)) {
                        rechargeWap(money, rechargeChannel.getPayChannel(), rechargeChannel.getCardType());
                    }
                } else if (rechargeChannel.getPayType().equals("unionscan")) {
                    payTypeTitle = "银联扫码";
                    if (rechargeYanZheng(money)) {
                        rechargeWap(money, rechargeChannel.getPayChannel(), rechargeChannel.getCardType());
                    }
                } else if (rechargeChannel.getPayType().equals("unionkj")) {
                    payTypeTitle = "银联快捷";
                    if (rechargeYanZheng(money)) {
                        rechargeWap(money, rechargeChannel.getPayChannel(), rechargeChannel.getCardType());
                    }
                } else if (rechargeChannel.getPayType().equals("offline")) {
                    payTypeTitle = "线下支付";
                    //线下支付默认金额
                    rechargeWap(String.valueOf(2), rechargeChannel.getPayChannel(), rechargeChannel.getCardType());
                } else if (rechargeChannel.getCardType().equals("yhkzk")) {
                    if (TextUtil.isEmpty(money)) {
                        showToast("请输入充值金额");
                    } else {
                        payTypeTitle = "银行卡转卡";
                        showYHKZKPopuo(money, rechargeChannel.getPayChannel(), rechargeChannel.getCardType());
                    }
                }
            }
        });

        return view;
    }

    YHKZKPopup yhkzkPopup;

    /**
     * 弹出银行卡转卡转款人姓名弹窗
     *
     * @param money
     * @param payChannel
     * @param cardType
     */
    private void showYHKZKPopuo(String money, String payChannel, String cardType) {
        if (yhkzkPopup != null) {
            if (yhkzkPopup.isShowing())
                yhkzkPopup.dismiss();
        }
        yhkzkPopup = new YHKZKPopup(getContext());
        yhkzkPopup.setOnClickListener(new YHKZKPopup.onClickListener() {
            @Override
            public void onCancelClick(BasePopupWindow popupWindow, View view) {

            }

            @Override
            public void onConfirmClick(BasePopupWindow popupWindow, View view, String content) {
                popupWindow.dismiss();
                rechargeYHKZK(money, payChannel, cardType, content);
            }
        });
        yhkzkPopup.showPopupWindow();
    }

    private Handler payHandler;

    private static class AliPayHandler extends Handler {
        private WeakReference<RechargeActivity> mActivity;

        AliPayHandler(RechargeActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            RechargeActivity activity = mActivity.get();
            if (activity != null) {
                activity.handleMessage(msg);
            }
        }
    }

    public void handleMessage(Message msg) {
        switch (msg.what) {
            case PaymentUtil.ALI_PAY://支付宝支付
                AliPayResult result = new AliPayResult((Map<String, String>) msg.obj);
                Log.e(TAG, "aliPayResult: " + result.toString());
                /**
                 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                 */
                String resultInfo = result.getResult();// 同步返回需要验证的信息
                String resultStatus = result.getResultStatus();
                // 判断resultStatus 为9000则代表支付成功
                if (TextUtils.equals(resultStatus, "9000")) {
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    paySuccess();
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    payFailure();
                }
                break;
            default:
                break;
        }
    }

    private void paySuccess() {
        AlertDialog rechargeSuccess = new AlertDialog.Builder(RechargeActivity.this)
                .setTitle("提示")
                .setMessage("充值成功")
                .setPositiveButton("继续", (dialog, which) -> dialog.cancel())
                .setNegativeButton("返回", (dialog, which) -> {
                    dialog.cancel();
                    resultActivityCode = IntentParamUtils.LOWMONEY_TO_RECHARGE_OK;
                    RechargeActivity.this.finish();
                }).create();
        rechargeSuccess.show();
    }

    private void payFailure() {
        resultActivityCode = IntentParamUtils.LOWMONEY_TO_RECHARGE_FAIL;
        AppToast.getToast().show("支付失败");
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            /**
             * do something
             * 如果msg.what == 0 表示操作成功，msg.what == 10001 则表示操作失败,
             * msg.what == 10002 则表示 支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，
             * 最终交易是否成功以服务端异步通知为准（小概率状态）
             */
            Log.i("wiki", "---------------:" + msg.what + "-----------------------");
            Log.i("wiki", "---------------:" + ((String) msg.obj).toString() +
                    "-----------------------");
            switch (msg.what) {

                case 0:
                    AlertDialog rechargeSuccess = new AlertDialog.Builder(RechargeActivity.this)
                            .setTitle("提示").setMessage("充值成功").setPositiveButton("继续", new
                                    DialogInterface.OnClickListener() {


                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.cancel();
                                        }
                                    }).setNegativeButton("返回", new DialogInterface
                                    .OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                    resultActivityCode = IntentParamUtils.LOWMONEY_TO_RECHARGE_OK;
                                    RechargeActivity.this.finish();
                                }
                            }).create();
                    rechargeSuccess.show();
                    break;
                case 10001:
                    resultActivityCode = IntentParamUtils.LOWMONEY_TO_RECHARGE_FAIL;
                    AppToast.getToast().show("支付失败");
                    break;
                case 10002:
                    resultActivityCode = IntentParamUtils.LOWMONEY_TO_RECHARGE_FAIL;
                    AppToast.getToast().show("支付等待确认");
                    break;
            }
        }

    };


    @Override
    protected void onFailure(int requestCode, String errorCode, String message) {
        super.onFailure(requestCode, errorCode, message);
//        if (errorCode.equals("5")) {
//            showToast("当前充值渠道暂不支持");
//        }
        if (!TextUtils.isEmpty(message)) {
            showToast(message);
        }
    }

    /**
     * 充值通道失败对话框
     */
    private AlertDialog failDialog = null;

    public void showFailDialog(String message) {

        if (failDialog == null) {
            failDialog = new AlertDialog.Builder(this).setTitle("温馨提示")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    }).create();
        }
        failDialog.setMessage(message);
        failDialog.show();
    }

    RadioGroup.OnCheckedChangeListener amountChangedListener = new RadioGroup
            .OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.recharge_money_50:
                    recharge_edt_amount.setText(100 + "");
                    break;
                case R.id.recharge_money_200:
                    recharge_edt_amount.setText(200 + "");
                    break;
                case R.id.recharge_money_500:
                    recharge_edt_amount.setText(500 + "");
                    break;
                case R.id.recharge_money_1000:
                    recharge_edt_amount.setText(1000 + "");
                    break;
            }
            recharge_edt_amount.setSelection(recharge_edt_amount.getText().length());
        }
    };
    RadioGroup.OnCheckedChangeListener rechargeTypeChangedListener = new RadioGroup
            .OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.recharge_type_bank:
                    ll_bank.setVisibility(View.VISIBLE);
                    ll_more.setVisibility(View.GONE);
                    ll_normal.setVisibility(View.GONE);
                    break;
                case R.id.recharge_type_normal:
                    ll_bank.setVisibility(View.GONE);
                    ll_more.setVisibility(View.GONE);
                    ll_normal.setVisibility(View.VISIBLE);
                    break;
                case R.id.recharge_type_more:
                    ll_bank.setVisibility(View.GONE);
                    ll_more.setVisibility(View.VISIBLE);
                    ll_normal.setVisibility(View.GONE);
                    break;

            }
        }
    };

    class ChongZhiOnClick implements OnClickListener {

        @Override
        public void onClick(View v) {
            Intent intent = null;
            switch (v.getId()) {
                case R.id.chz_center_zhifubao_wap:
                    intent = new Intent(RechargeActivity.this, Recharge_AlipayWapActivity.class);
                    break;
                case R.id.chz_center_zhifubao_expresss:
                    intent = new Intent(RechargeActivity.this, CZ_AlipayExpress.class);
                    break;
                case R.id.chz_center_yibao:
                    AppToast.getToast().show("建设中...");
                    break;
                case R.id.chz_center_yinlian:
                    intent = new Intent(RechargeActivity.this, CZ_YL_JAR.class);
                    break;
                case R.id.chz_center_jd:
                    intent = new Intent(RechargeActivity.this, CZ_JD.class);
                    break;
                default:
                    break;
            }
            if (intent != null) {
                startActivity(intent);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, final int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.EXPRESS_SMC_REQUEST_CODE && resultCode == Constants
                .EXPRESS_SMC_RESULT_CODE) {
            String returnValue = data.getStringExtra(Constants.EXPRESS_SMC_RETURN_VALUE);
            if (TransStatus.isSuccess(returnValue)) {
                //支付成功android.permission.READ_PHONE_STATE
                new AlertDialog.Builder(this).setMessage("充值成功").setPositiveButton("确定", new
                        DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                resultActivityCode = IntentParamUtils.LOWMONEY_TO_RECHARGE_OK;
                                RechargeActivity.this.finish();
                            }
                        }).create().show();
            } else if (TransStatus.isFailed(returnValue)) {
                //支付失败
                resultActivityCode = IntentParamUtils.LOWMONEY_TO_RECHARGE_FAIL;
            } else {
                //未完成支付
                resultActivityCode = IntentParamUtils.LOWMONEY_TO_RECHARGE_FAIL;
                showToast("取消支付");
            }
        }

    }

}
